package com.nantian.common.io;

import org.apache.commons.codec.CharEncoding;

import java.io.*;

/**
 * <p>ClassName: StreamUtils</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright©2014</p>
 * <p>Company: 广州南天电脑系统有限公司</p>
 * <p>Date: 2020-05-22</p>
 *
 * @author 刘晓辉
 * @version 1.0
 */
public class StreamUtils {
    public static byte[] readInputStreamToByteArray(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1){
            outStream.write(buffer,0, len);
        }
        return outStream.toByteArray();
    }
    public static String readInputStreamToString(InputStream inStream) throws IOException{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=inStream.read(buffer)) != -1){
            outStream.write(buffer,0,len);
        }
        try {
            String str = outStream.toString(CharEncoding.UTF_8);
            return str;
        } finally {
            if (outStream != null) {
                outStream.close();
            }
        }



    }
    public static File readInputStreamToFile(InputStream inStream , File file) throws IOException{
        @SuppressWarnings("resource")
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len=0;
            while ((len=inStream.read(buffer))!=-1){
                outStream.write(buffer,0,len);
            }
            return file;
        } finally {
            if (outStream != null) {
                outStream.close();
            }
        }


    }
    public static File readInputStreamToFile(InputStream inStream , String filepath , String key) throws IOException{
        File file = File.createTempFile(filepath, key);
        return readInputStreamToFile(inStream ,file);

    }
}
